import { useState, useEffect } from "react";
import CommonModal from "@/components/CommonModal";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { Select, Form, message } from "antd";
import { saveCodePrintTask, getKuaiMaiPrint } from '../service';
import { printKmUniqcode } from '@/utils/printKm.js';
import { getAllPrinter } from "@/utils/print.jsx";
import { getExpressRelativePrinter, setExpressRelativePrinter } from "@/utils/authority";

const { Option } = Select;

const PrintModal = ({ printParams, handleCancel }) => {

	const [form] = Form.useForm();

	//是否正在打印
	const [isPrint, setIsPrint] = useState(false);

	const [open, setOpen] = useState(false);

	const [printList, setPrintList] = useState([]);

	//默认打印机列表
	const printObj = getExpressRelativePrinter() || {};

	useEffect(() => {
		setOpen(true);
		getAllPrinter(val => {
			setPrintList(val);
		});
		form.setFieldsValue({
			printer: printObj["快销退货条码"]
		});
	}, []);

	// 设置打印机名称
	const handlePrinterName = name => {
		setExpressRelativePrinter({
			...printObj,
			"快销退货条码": name
		});
	};

	//获取打印数据推入队列
	const onOk = () => {
		if (!printParams?.length) {
			return message.info("打印数据为空");
		}
		form.validateFields().then(async value => {
			if (!value) {
				return message.info("请选择打印机");
			}
			if (isPrint) {
				return message.info('打印作业正在进行中，请勿重复提交');
			}
			START_LOADING();
			const res = await getKuaiMaiPrint({
				codes: printParams.map(v => v.uniqueCode),
				labelType: 6
			})
			END_LOADING();
			if (res.success) {
				setIsPrint(true);
				message.info('即将开始打印');
				printKmUniqcode(JSON.parse(res.data), value["printer"], () => {
					savePrintRecord(value["printer"]);
					setIsPrint(false);
					setOpen(false);
				});
			}
		});
	};

	//保存打印记录
	const savePrintRecord = (value) => {
		const arr = [];
		printParams.map(v => {
			arr.push({
				"outboundNo": v.outboundNo,
				"uniqueCode": v.uniqueCode
			})
		})
		saveCodePrintTask({
			printerName: value,
			printPageType: 5,
			codePrintSaveVOList: arr
		})
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		handleCancel();
	}

	const options = (
		Array.isArray(printList) &&
		printList.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		))
	)

	return (
		<CommonModal
			title="打印快销退货条码"
			open={open}
			onCancel={onCancel}
			afterClose={afterClose}
			width="469px"
			onOk={onOk}
		>
			<Form form={form} name="common-printer-select">
				<SubTitle symbol as="s2" title={`打印机`} wrapStyle={{ marginBottom: 16 }} />
				<Form.Item label="" name="printer" style={{ margin: 8 }} rules={[{ required: true, message: "请先选择打印机" }]}>
					<Select placeholder="请选择打印机" onChange={handlePrinterName}>
						{options}
					</Select>
				</Form.Item>
				<Form.Item style={{ margin: '24px 0 0 12px' }}>
					<div>
						<span>本次打印数量：</span>
						<span>{printParams.length}</span>
					</div>
				</Form.Item>
			</Form>
		</CommonModal>
	);
};

export default PrintModal;
